<?php

use service\DataService;
use service\NodeService;
use think\Db;
use think\Image;
use think\facade\Env;
use service\FileService;
use JPush\Client as JPush;
use think\facade\App;
use service\ToolsService;

function getUA()
{
    if (isset($_SERVER['HTTP_USER_AGENT'])) {
        return $_SERVER['HTTP_USER_AGENT'];
    } else {
        return '';
    }
}

/**
 * 获取客户端浏览器以及版本号  https://blog.csdn.net/qq_42176520/article/details/100701351
 * @param $agent    //$_SERVER['HTTP_USER_AGENT']
 * @return array[browser]       浏览器名称
 * @return array[browser_ver]   浏览器版本号
 */
function getClientBrowser($agent = '') {
    $browser = '';
    $browser_ver = '';
    if (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
        $browser = 'OmniWeb';
        $browser_ver = $regs[2];
    }
    if (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Netscape';
        $browser_ver = $regs[2];
    }
    if (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Safari';
        $browser_ver = $regs[1];
    }
    if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
        $browser = 'Internet Explorer';
        $browser_ver = $regs[1];
    }
    if (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
        $browser = 'Opera';
        $browser_ver = $regs[1];
    }
    if (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
        $browser = '(Internet Explorer '.$browser_ver.') NetCaptor';
        $browser_ver = $regs[1];
    }
    if (preg_match('/Maxthon/i', $agent, $regs)) {
        $browser = '(Internet Explorer '.$browser_ver.') Maxthon';
        $browser_ver = '';
    }
    if (preg_match('/360SE/i', $agent, $regs)) {
        $browser = '(Internet Explorer '.$browser_ver.') 360SE';
        $browser_ver = '';
    }
    if (preg_match('/SE 2.x/i', $agent, $regs)) {
        $browser = '(Internet Explorer '.$browser_ver.') 搜狗';
        $browser_ver = '';
    }
    if (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'FireFox';
        $browser_ver = $regs[1];
    }
    if (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Lynx';
        $browser_ver = $regs[1];
    }
    if (preg_match('/Chrome\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Chrome';
        $browser_ver = $regs[1];
    }
    if (preg_match('/MicroMessenger\/([^\s]+)/i', $agent, $regs)) {
        $browser = '微信浏览器';
        $browser_ver = $regs[1];
    }
    if ($browser != '') {
        return ['browser'=>$browser, 'browser_ver'=>$browser_ver];
    } else {
        return ['browser'=>'未知','browser_ver'=> ''];
    }
}

/**
 * 获取客户端操作系统     https://blog.csdn.net/qq_42176520/article/details/100701351
 * @param $agent //$_SERVER['HTTP_USER_AGENT']
 * @return array[os]            操作系统名称
 * @return array[os_ver]        操作系统版本号
 * @return array[equipment]     终端设备类型
 */
function getClientOS($agent = '')
{
    //window系统
    if (stripos($agent, 'window')) {
        $os = 'Windows';
        $equipment = '电脑';
        if (preg_match('/nt 6.0/i', $agent)) {
            $os_ver = 'Vista';
        } elseif (preg_match('/nt 10.0/i', $agent)) {
            $os_ver = '10';
        } elseif (preg_match('/nt 6.3/i', $agent)) {
            $os_ver = '8.1';
        } elseif (preg_match('/nt 6.2/i', $agent)) {
            $os_ver = '8.0';
        } elseif (preg_match('/nt 6.1/i', $agent)) {
            $os_ver = '7';
        } elseif (preg_match('/nt 5.1/i', $agent)) {
            $os_ver = 'XP';
        } elseif (preg_match('/nt 5/i', $agent)) {
            $os_ver = '2000';
        } elseif (preg_match('/nt 98/i', $agent)) {
            $os_ver = '98';
        } elseif (preg_match('/nt/i', $agent)) {
            $os_ver = 'nt';
        } else {
            $os_ver = '';
        }
        if (preg_match('/x64/i', $agent)) {
            $os .= '(x64)';
        } elseif (preg_match('/x32/i', $agent)) {
            $os .= '(x32)';
        }
    } elseif (stripos($agent, 'linux')) {
        if (stripos($agent, 'android')) {
            preg_match('/android\s([\d\.]+)/i', $agent, $match);
            $os = 'Android';
            $equipment = 'Mobile phone';
            $os_ver = $match[1];
        } else {
            $os = 'Linux';
            $os_ver = '';
            $equipment = '';
        }
    } elseif (stripos($agent, 'unix')) {
        $os = 'Unix';
        $os_ver = '';
        $equipment = '';
    } elseif (preg_match('/iPhone|iPad|iPod/i', $agent)) {
        preg_match('/OS\s([0-9_\.]+)/i', $agent, $match);
        $os = 'IOS';
        $os_ver = str_replace('_', '.', $match[1]);
        $equipment = '';
        if (preg_match('/iPhone/i', $agent)) {
            $equipment = 'iPhone';
        } elseif (preg_match('/iPad/i', $agent)) {
            $equipment = 'iPad';
        } elseif (preg_match('/iPod/i', $agent)) {
            $equipment = 'iPod';
        }
    } elseif (stripos($agent, 'mac os')) {
        preg_match('/Mac OS X\s([0-9_\.]+)/i', $agent, $match);
        $os = 'Mac OS X';
        $equipment = '电脑';
        $os_ver = str_replace('_', '.', $match[1]);
    } else {
        $os = 'Other';
        $os_ver = '';
        $equipment = '';
    }
    return ['os' => $os, 'os_ver' => $os_ver, 'equipment' => $equipment];
}

/**
 * 获取客户端手机型号  https://blog.csdn.net/qq_42176520/article/details/100701351
 * @param $agent //$_SERVER['HTTP_USER_AGENT']
 * @return array[mobile_brand]      手机品牌
 * @return array[mobile_ver]        手机型号
 */
function getClientMobileBrand($agent = '')
{
    if (preg_match('/iPhone\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '苹果';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/SAMSUNG|Galaxy|GT-|SCH-|SM-\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '三星';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/Huawei|Honor|H60-|H30-\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '华为';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/Mi note|mi one\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '小米';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/HM NOTE|HM201\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '红米';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/Coolpad|8190Q|5910\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '酷派';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/ZTE|X9180|N9180|U9180\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '中兴';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/OPPO|X9007|X907|X909|R831S|R827T|R821T|R811|R2017\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = 'OPPO';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/HTC|Desire\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = 'HTC';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/Nubia|NX50|NX40\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '努比亚';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/M045|M032|M355\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '魅族';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/Gionee|GN\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '金立';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/HS-U|HS-E\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '海信';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/Lenove\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '联想';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/ONEPLUS\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '一加';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/vivo\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = 'vivo';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/K-Touch\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '天语';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/DOOV\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '朵唯';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/GFIVE\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '基伍';
        $mobile_ver = $regs[0];
    } elseif (preg_match('/Nokia\s([^\s|;]+)/i', $agent, $regs)) {
        $mobile_brand = '诺基亚';
        $mobile_ver = $regs[0];
    } else {
        $mobile_brand = '其他';
        $mobile_ver = '';
    }
    return ['mobile_brand' => $mobile_brand, 'mobile_ver' => $mobile_ver];
}

function getMobileBrand()
{
    $user_agent = $_SERVER['HTTP_USER_AGENT'];

    if (stripos($user_agent, "iPhone") !== false) {
        $brand = 'iPhone';

    } else if (stripos($user_agent, "SAMSUNG") !== false || stripos($user_agent, "Galaxy") !== false || strpos($user_agent, "GT-") !== false || strpos($user_agent, "SCH-") !== false || strpos($user_agent, "SM-") !== false) {
        $brand = '三星';

    } else if (stripos($user_agent, "Huawei") !== false || stripos($user_agent, "Honor") !== false || stripos($user_agent, "H60-") !== false || stripos($user_agent, "H30-") !== false) {
        $brand = '华为';

    } else if (stripos($user_agent, "Lenovo") !== false) {
        $brand = '联想';

    } else if (strpos($user_agent, "MI-ONE") !== false || strpos($user_agent, "MI 1S") !== false || strpos($user_agent, "MI 2") !== false || strpos($user_agent, "MI 3") !== false || strpos($user_agent, "MI 4") !== false || strpos($user_agent, "MI-4") !== false) {
        $brand = '小米';

    } else if (strpos($user_agent, "HM NOTE") !== false || strpos($user_agent, "HM201") !== false) {
        $brand = '红米';

    } else if (stripos($user_agent, "Coolpad") !== false || strpos($user_agent, "8190Q") !== false || strpos($user_agent, "5910") !== false) {
        $brand = '酷派';

    } else if (stripos($user_agent, "ZTE") !== false || stripos($user_agent, "X9180") !== false || stripos($user_agent, "N9180") !== false || stripos($user_agent, "U9180") !== false) {
        $brand = '中兴';

    } else if (stripos($user_agent, "OPPO") !== false || strpos($user_agent, "X9007") !== false || strpos($user_agent, "X907") !== false || strpos($user_agent, "X909") !== false || strpos($user_agent, "R831S") !== false || strpos($user_agent, "R827T") !== false || strpos($user_agent, "R821T") !== false || strpos($user_agent, "R811") !== false || strpos($user_agent, "R2017") !== false) {
        $brand = 'OPPO';

    } else if (strpos($user_agent, "HTC") !== false || stripos($user_agent, "Desire") !== false) {
        $brand = 'HTC';

    } else if (stripos($user_agent, "vivo") !== false) {
        $brand = 'vivo';

    } else if (stripos($user_agent, "K-Touch") !== false) {
        $brand = '天语';

    } else if (stripos($user_agent, "Nubia") !== false || stripos($user_agent, "NX50") !== false || stripos($user_agent, "NX40") !== false) {
        $brand = '努比亚';

    } else if (strpos($user_agent, "M045") !== false || strpos($user_agent, "M032") !== false || strpos($user_agent, "M355") !== false) {
        $brand = '魅族';

    } else if (stripos($user_agent, "DOOV") !== false) {
        $brand = '朵唯';

    } else if (stripos($user_agent, "GFIVE") !== false) {
        $brand = '基伍';

    } else if (stripos($user_agent, "Gionee") !== false || strpos($user_agent, "GN") !== false) {
        $brand = '金立';

    } else if (stripos($user_agent, "HS-U") !== false || stripos($user_agent, "HS-E") !== false) {
        $brand = '海信';

    } else if (stripos($user_agent, "Nokia") !== false) {
        $brand = '诺基亚';

    } else {
        $brand = '其他手机';

    }
    return $brand;
}

function getIpInfo($ip)
{
    $url = "http://ip.taobao.com/outGetIpInfo?accessKey=alibaba-inc&ip=" . $ip;
    $result = json_decode(api_notice_increment($url), true);
    if ($result && $result['code'] == 0) {
        return $result['data'];
    } else {
        return [];
    }
}


function cossts()
{

    $tempKeys = \think\facade\Cache::get('cossts');
    if (!$tempKeys) {
        $sts = new \QCloud\COSSTS\Sts();
        $config = array(
            'url' => 'https://sts.tencentcloudapi.com/',
            'domain' => 'sts.tencentcloudapi.com',
            'secretId' => 'AKID0qSoukQ1SlqfEWedZO9i262nJqHVUEj5',
            'secretKey' => 'IQfgSzGH3at0tXv4xbzQcaIkyxjHafT1',
            'bucket' => 'jtyh-1304110122',
            'region' => 'ap-guangzhou',
            'durationSeconds' => 7200, //过期时间 秒 最大7200
            'allowPrefix' => '*', // 全部权限
            'allowActions' => array(// 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject', // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            )

        );
        // 获取临时密钥，计算签名
        $tempKeys = $sts->getTempKeys($config);
        if ($tempKeys && $tempKeys['credentials']) {
            \think\facade\Cache::set('cossts', $tempKeys, 7000);
        }
    }

    return $tempKeys;
}


function createPhoneCode($length = 4)
{
    $pool = '1234567890';
    $str = '';
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($pool, mt_rand(0, strlen($pool) - 1), 1);
    }

    return $str;
}

if (!function_exists('isMobile')) {
    /**
     * 判断当前访问的用户是  PC端  还是 手机端  返回true 为手机端  false 为PC 端
     *
     * @return bool
     */
    function isMobile()
    {
        // 如果有HTTP_X_WAP_PROFILE则一定是移动设备
        if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
            return true;

        // 如果via信息含有wap则一定是移动设备,部分服务商会屏蔽该信息
        if (isset ($_SERVER['HTTP_VIA'])) {
            // 找不到为flase,否则为true
            return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
        }
        // 脑残法，判断手机发送的客户端标志,兼容性有待提高
        if (isset ($_SERVER['HTTP_USER_AGENT'])) {
            $clientkeywords = array('nokia', 'sony', 'ericsson', 'mot', 'samsung', 'htc', 'sgh', 'lg', 'sharp', 'sie-', 'philips', 'panasonic', 'alcatel', 'lenovo', 'iphone', 'ipod', 'blackberry', 'meizu', 'android', 'netfront', 'symbian', 'ucweb', 'windowsce', 'palm', 'operamini', 'operamobi', 'openwave', 'nexusone', 'cldc', 'midp', 'wap', 'mobile');
            // 从HTTP_USER_AGENT中查找手机浏览器的关键字
            if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
                return true;
        }
        // 协议法，因为有可能不准确，放到最后判断
        if (isset ($_SERVER['HTTP_ACCEPT'])) {
            // 如果只支持wml并且不支持html那一定是移动设备
            // 如果支持wml和html但是wml在html之前则是移动设备
            if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
                return true;
            }
        }

        return false;
    }
}

function tip_alert($msg)
{
    $media_contet = "<!DOCTYPE html>
<html lang=\"en\">

<head>
    <meta charset=\"UTF-8\">
    <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">
    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">
    <title>提示</title>
</head>

<body>
 <div class='demo-bg'></div>
        <div class='demo-txt'>
            <div class=\"message\">
                <div class=\"message_title\">提示</div>
                <div class=\"message_body\">
                    {$msg}
                </div>
                <button onclick=\"closeDialog()\">关闭</button>
            </div>
        </div>

<style>
.demo-txt {
    position: absolute;
    z-index: 1000;
    color: #000;
    background: white;
    width: 80%;
    height: 100px;
    margin: auto;
    left: 0;
    right: 0;
    bottom: 0;
    top: 0;
    display: block;
    padding: 10px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
}

#btn {
    float: right;
}

.message {
    text-align: center;
}

.message .message_title {
    font-size: 0.9rem;
    padding-bottom: 0.5rem;
}

.message .message_body {
    font-size: 0.85rem;
    height: 2rem;
}

.message button {
    padding: 0.3rem 1rem;
    background-color: #ff3300;
    color: #fff;
    border-radius: 0.3rem;
}
.demo-bg {
    position: absolute;
    left: 0;
    top: 0;
    z-index: 999;
    width: 100%;
    min-height: 100vh;
    background-color: rgba(0, 0, 0, 0.4);
    display: block;
}
button {
    cursor: pointer;
    outline: none;
    border: 0;
}
</style>

<script>
    var demobg = document.querySelector(\".demo-bg\");
    var demotxt = document.querySelector(\".demo-txt\");
    function closeDialog() {
        demotxt.style.display = \"none\";
        demobg.style.display = \"none\";
    }
</script>
</body>

</html>";

    $content = <<<HTML
{$media_contet}
HTML;

    $expire = 0;
    header('Content-Type:text/html;charset=utf-8');
    header('Cache-Control: max-age=' . $expire);
    header('Accept-Ranges: bytes');
    header('Content-Length: ' . strlen($content));
    echo $content;
    exit();

}

/**
 * @param $total [你要发的红包总额]
 * @param int $num [发几个]
 * @return array[生成红包金额]
 */
function getRedGift($total, $num = 10)
{
    $min = 0.3;
    $wamp = array();
    $returnData = array();
    for ($i = 1; $i < $num; ++$i) {
        $safe_total = ($total - ($num - $i) * $min) / ($num - $i); //红包金额的最大值
        if ($safe_total < 0) break;
        $money = @mt_rand($min * 100, $safe_total * 100) / 100;//随机产生一个红包金额
        $total = $total - $money;//剩余红包总额
        $wamp[$i] = round($money, 2);//保留两位有效数字
    }
    $wamp[$i] = round($total, 2);
    $returnData['MoneySum'] = $wamp;
    $returnData['newTotal'] = array_sum($wamp);
    return $returnData;
}


function api_notice_increment($url)
{
    header("Content-Type:text/html;charset=utf-8");
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $result = curl_exec($curl);
    if (curl_errno($curl)) {
        return false;
    } else {
        return $result;
    }
}

/**
 *
 * 模糊搜索数组
 * $data 数组
 * $key 匹配字符串
 * $info 字段
 **/
function arr_likes($data, $key, $info)
{
    $arr = array();
    foreach ($data as $k => $v) {
        if (strstr($v[$info], $key) !== false) {
            array_push($arr, $v);
        }
    }
    return $arr;
}

/*

* array unique_rand( int $min, int $max, int $num )
* 生成一定数量的不重复随机数
* $min 和 $max: 指定随机数的范围
* $num: 指定生成数量
*/

function unique_rand($min, $max, $num)
{
    $count = 0;
    $return = array();
    while ($count < $num) {
        $return[] = mt_rand($min, $max);
        $return = array_flip(array_flip($return));
        $count = count($return);
    }
    shuffle($return);

    return $return;

}

/**
 * 总会员数
 * @return int
 */
function total_member_count()
{
    $result = Db::name('tp_member')
        ->cache('total_member_count', 60)
        ->count();

    return $result;
}

/**
 * 会员昵称转换
 * @param $name
 * @return string
 */
function getMemberNickName($name)
{

    return ToolsService::emojiDecode($name);
}


/**推送信息到手机
 * @param $text (消息标题)
 * @param string $desp (消息内容)
 * @param string $key
 * @return bool|string
 */
function sc_send($text, $desp = '', $key = 'SCU23165Tcc436acd29f7270218c5d753bbe72dd75aa9c4020fd26')
{
    $postdata = http_build_query(
        array(
            'text' => $text,
            'desp' => $desp
        )
    );

    $opts = array('http' =>
        array(
            'method' => 'POST',
            'header' => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );
    $context = stream_context_create($opts);
    return $result = file_get_contents('https://sc.ftqq.com/' . $key . '.send', false, $context);

}

/**
 * 截取字符串
 * @param $text
 * @param $length
 * @return string
 */
function subtext($text, $length)
{
    if (mb_strlen($text, 'utf8') > $length)
        return mb_substr($text, 0, $length, 'utf8') . '...';
    return $text;
}

/**
 * 过滤emoji表情
 * @param $str
 * @return mixed
 */
function filter_emoji($str)
{
    $str = preg_replace_callback(
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);
    return $str;
}

/**
 * 手机号格式检查
 * @param string $mobile
 * @return bool
 */
function check_mobile_number($mobile)
{
    if (!is_numeric($mobile)) {
        return false;
    }
//    $reg = '#^13[\d]{9}$|^14[\d]{9}$|^15[\d]{9}$|^16[\d]{9}$|^17[\d]{9}$|^18[\d]{9}$|^19[\d]{9}$#';
    $reg = "/^1[3456789]\d{9}$/";
    return preg_match($reg, $mobile) ? true : false;
}

/**
 * 普通短信发送
 * @param $mobile
 * @param $msg
 * @return bool|string
 */
function send_sms_to_mobile($mobile, $msg)
{
    if (empty($msg)) {
        return '短信内容为空？写点吧～';
    }

    $statusStr = array(
        "0" => "短信发送成功",
        "-1" => "参数不全",
        "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
        "30" => "密码错误",
        "40" => "账号不存在",
        "41" => "余额不足",
        "42" => "帐户已过期",
        "43" => "IP地址限制",
        "50" => "内容含有敏感词"
    );
    $smsapi = "http://api.smsbao.com/";
    $user = "sheyingtg"; //短信平台帐号
    $pass = md5("yongge8685"); //短信平台密码

    $sendurl = $smsapi . "sms?u=" . $user . "&p=" . $pass . "&m=" . $mobile . "&c=" . urlencode($msg);
    $result = file_get_contents($sendurl);
//echo $statusStr[$result];

    if ($result == 0) {
        return true;
    } else {
        return false;
    }
}


/**
 * 中转短信发送
 * @param $mobile
 * @param $msg
 * @return bool|string
 */
function send_sms_to_zz($mobile, $msg)
{
    if (empty($msg)) {
        return '短信内容为空？写点吧～';
    }
    $config = config('other.mobile_sms');
    $api_send_url = $config['api_zz_url'];
    $sign = md5('zycmsms@' . $mobile);;

    //创蓝接口参数
    $postArr = array(
        'mobile' => $mobile,
        'msg' => $config['tail'] . $msg,
        'sign' => $sign
    );

    $client = new \GuzzleHttp\Client(['verify' => false]);
    $data = $client->request('Get', $api_send_url,
        [
            'query' => $postArr
        ]
    );
    $result = json_decode($data->getBody(), true);

    if ($result['code'] == 0) {
        return true;
    } else {
        return false;
    }
}


/**
 * 处理返回值
 * @param $result
 * @return array|false|string[]
 */
function execResult($result)
{
    $result = preg_split("/[,\r\n]/", $result);
    return $result;
}

/**
 * 通过CURL发送HTTP请求
 * @param string $url //请求URL
 * @param array $postFields //请求参数
 * @return mixed
 */
function curlPost($url, $postFields)
{
    $postFields = http_build_query($postFields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //curl抓取页面时遇到重定向的解决方法
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

/**
 * curl请求指定url
 * @param $url
 * @param array $data
 * @return mixed
 */
function curl($url, $data = [])
{
    // 处理get数据
    if (!empty($data)) {
        $url = $url . '?' . http_build_query($data);
    }
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HEADER, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//这个是重点。
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

/**
 * 自定义生成json格式
 * @param $code
 * @param string $msg
 * @param array $data
 */
function diyJson($code, $msg = "", $data = array())
{
    $result = array(
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    );
    //输出json
    echo json_encode($result);
    exit;
}


/**
 * 网点号生成
 * @return string
 */
function build_shop_no_()
{
    $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
    $shop_no = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
    return $shop_no;
}

/**
 * 生成优惠券
 * @param $length
 * @param string $char_str
 * @return string
 */
function build_coupon($length, $char_str = '123456789')
{
    $hash = '';
    $chars = $char_str;
    $max = strlen($chars);
    for ($i = 0; $i < $length; $i++) {
        $hash .= substr($chars, (rand(0, 1000) % $max), 1);
    }
    return $hash;
}

/**
 * 订单号生成
 * @param int $length
 * @return string
 */
function build_order_no($length = 8)
{
    return date('YmdHis') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, $length);
}


/**
 * 打赏交易号生成
 * @param int $member_id
 * @param int $theme_id
 * @return string
 */
function build_out_trade_no($member_id = 0, $theme_id = 0)
{
    $rand_id = rand(1000, 9999);
    $out_trade_no = "award-{$member_id}-{$theme_id}-{$rand_id}";
    return $out_trade_no;
}


/**
 * 删除空格
 * @param $str
 * @return mixed
 */
function TrimAll($str)
{
    $qian = array(" ", "　", "\t", "\n", "\r");
    $hou = array("", "", "", "", "");
    return str_replace($qian, $hou, $str);
}

/**
 * @param $data
 */
function print_dump($data)
{
    echo "<pre>";
    print_r($data);
    die;
}

/**
 * RBAC节点权限验证
 * @param string $node
 * @return bool
 */
function auth($node)
{
    return NodeService::checkAuthNode($node);
}

/**
 * 设备或配置系统参数
 * @param string $name 参数名称
 * @param bool $value 默认是null为获取值，否则为更新
 * @return string|bool
 * @throws \think\Exception
 * @throws \think\exception\PDOException
 */
function sysconf($name, $value = null)
{
    static $config = [];
    if ($value !== null) {
        list($config, $data) = [[], ['name' => $name, 'value' => $value]];
        cache('system_config', null);
        return DataService::save('SystemConfig', $data, 'name');
    }
    if (empty($config)) {
        $config = Db::name('SystemConfig')->cache('system_config', 7200 * 2)->column('name,value');
    }
    return isset($config[$name]) ? $config[$name] : '';
}


/**
 * 日期格式标准输出
 * @param string $datetime 输入日期
 * @param string $format 输出格式
 * @return false|string
 */
function format_datetime($datetime, $format = 'Y年m月d日 H:i:s')
{
    return date($format, strtotime($datetime));
}

/**
 * UTF8字符串加密
 * @param string $string
 * @return string
 */
function encode($string)
{
    list($chars, $length) = ['', strlen($string = iconv('utf-8', 'gbk', $string))];
    for ($i = 0; $i < $length; $i++) {
        $chars .= str_pad(base_convert(ord($string[$i]), 10, 36), 2, 0, 0);
    }
    return $chars;
}

/**
 * UTF8字符串解密
 * @param string $string
 * @return string
 */
function decode($string)
{
    $chars = '';
    foreach (str_split($string, 2) as $char) {
        $chars .= chr(intval(base_convert($char, 36, 10)));
    }
    return iconv('gbk', 'utf-8', $chars);
}

/**
 * 下载远程文件到本地
 * @param string $url 远程图片地址
 * @return string
 */
function local_image($url)
{
    return \service\FileService::download($url)['url'];
}


/**
 * 上传图片(base64)
 * @param $base64
 * @return bool|array
 */
function base64_upload($base64_img)
{

    $up_dir = 'static/upload/';//存放在当前目录的upload文件夹下

    if (!file_exists($up_dir)) {
        mkdir($up_dir, 0777);
    }

    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)) {
        $type = $result[2];
        if (in_array($type, array('pjpeg', 'jpeg', 'jpg', 'gif', 'bmp', 'png'))) {
            $filename = date('YmdHis') . rand(10000, 99999) . '.' . $type;
            $new_file = $up_dir . $filename;
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))) {

                //生成缩略图
//                image_edit('/upload/' . $filename, 800, 800);

                if (sysconf('storage_type') === 'oss') {
                    $url = FileService::oss($new_file, App::getRootPath() . $new_file, 1)['url'];
                } elseif (sysconf('storage_type') === 'qiniu') {
                    $url = FileService::qiniu($new_file, file_get_contents(App::getRootPath() . $new_file))['url'];
                } elseif (sysconf('storage_type') === 'cos') {
                    $url = FileService::cos($new_file, file_get_contents(App::getRootPath() . $new_file))['url'];
                } else {
//                        $url = request()->root(true) . '/' . $new_file;
//                    $url = config('cdn_url') . '/' . $new_file;
                    $url = sysconf('cdn_url') . '/upload/' . $filename;
                }

                return $url;

            } else {
                return false;
            }
        } else {
            return false;
        }

    } else {
        return false;
    }

}


/**
 * 单文件上传
 * @param $file
 * @param $width
 * @return array|string|\think\response\Json
 */
function upload($file, $width)
{
    if (sysconf('storage_type') === 'oss') {
        return upload_by_oss($file);
    } elseif (sysconf('storage_type') === 'qiniu') {
        return upload_by_qiniu($file);
    } elseif (sysconf('storage_type') === 'cos') {
        return upload_by_cos($file, $width);
    } else {
        return upload_by_local($file);
    }

}

/**
 * 单文件上传
 * @param $file
 * @return array|string|\think\response\Json
 */
function upload_by_local($file)
{
    if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
        return json(['code' => '1', 'message' => '文件上传类型受限']);
    }
    $pathinfo = pathinfo($file->getInfo('name'));
    $ext = strtolower(pathinfo($file->getInfo('name'), 4));
    $names = str_split($file->hash(), 16);
    $filename = "{$names[0]}/{$names[1]}.{$ext}";
    $savename = $names[1] . '.' . $ext;

    // 文件上传处理
    if (($info = $file->move("static/upload/{$names[0]}", $savename, true))) {
        if (($site_url = FileService::getFileUrl($filename, 'local'))) {

            $path = '/upload/' . $names[0] . '/' . $info->getSaveName();

//            if ($ext == 'jpg' || $ext == 'gif' || $ext == 'png') {
//                //裁剪图片
//                image_edit($path, 1000, 0);
//            }

            $data = [
                'filename' => $pathinfo['filename'],
//                'url' => request()->root(true) . $site_url,
                'url' => $site_url,
            ];

            return $data;
//            return request()->root(true) . $site_url;
        }
    }
    return '';

}

/**
 * 单文件上传(oss)
 * @param $file
 * @return array|string|\think\response\Json
 */
function upload_by_oss($file)
{
    if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
        return json(['code' => '1', 'message' => '文件上传类型受限']);
    }
    $pathinfo = pathinfo($file->getInfo('name'));
    $ext = strtolower(pathinfo($file->getInfo('name'), 4));
    $names = str_split($file->hash(), 16);
    $tmp_name = $file->getInfo('tmp_name');
    $filename = "{$names[0]}/{$names[1]}.{$ext}";

    $object = "static/upload/$filename";
    //上传到阿里云oss
    FileService::oss($object, file_get_contents($tmp_name));
    $site_url = FileService::getBaseUriOss() . $object;

    $data = [
        'filename' => $pathinfo['filename'],
        'url' => $site_url,
    ];
    return $data;

}


/**
 * 单文件上传(cos)
 * @param $file
 * @param int $width
 * @return array|\think\response\Json
 */
function upload_by_cos($file, $width)
{
    if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
        return json(['code' => '1', 'message' => '文件上传类型受限']);
    }
    $pathinfo = pathinfo($file->getInfo('name'));
    $ext = strtolower(pathinfo($file->getInfo('name'), 4));
    $names = str_split($file->hash(), 16);
    $tmp_name = $file->getInfo('tmp_name');
    $filename = "{$names[0]}_{$names[1]}.{$ext}";

    if (($file->move("static/upload/", $filename, true))) {
        //生成缩略图
//        image_edit('/upload/' . $filename, $width, 0); //高度为0，以宽度等比例缩小
    }

    $object = "static/upload/$filename";
    //上传到腾讯云cos

    FileService::cos($object, file_get_contents(App::getRootPath() . $object));
    unlink($object);
//    FileService::cos($object, file_get_contents($tmp_name));
    $site_url = FileService::getBaseUriCos() . $object;

    $data = [
        'filename' => $pathinfo['filename'],
        'url' => $site_url,
    ];
    return $data;

}

/**
 * 单文件上传(qiniu)
 * @param $file
 * @return array|string|\think\response\Json
 */
function upload_by_qiniu($file)
{
    if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
        return json(['code' => '1', 'message' => '文件上传类型受限']);
    }
    $pathinfo = pathinfo($file->getInfo('name'));
    $ext = strtolower(pathinfo($file->getInfo('name'), 4));
    $names = str_split($file->hash(), 16);
    $tmp_name = $file->getInfo('tmp_name');
    $filename = "{$names[0]}/{$names[1]}.{$ext}";

    $object = "static/upload/$filename";
    //上传到阿里云oss
    FileService::qiniu($object, file_get_contents($tmp_name));
    $site_url = FileService::getBaseUriQiniu() . $object;

    $data = [
        'filename' => $pathinfo['filename'],
        'url' => $site_url,
    ];
    return $data;

}

/**
 * 上传文件
 * @param $files
 * @param int $type
 */
function upload_files($files, $type = 0)
{
    if (sysconf('storage_type') === 'oss') {
        return upload_files_by_oss($files, $type);
    } elseif (sysconf('storage_type') === 'qiniu') {
        return upload_files_by_qiniu($files, $type);
    } else {
        return upload_files_by_local($files, $type);
    }
}


/**
 * 多文件上传图片(local)
 * @param $files
 * @param int $type
 * @return array|\think\response\Json
 */
function upload_files_by_local($files, $type = 0)
{
    $pics = [];
    foreach ($files as $file) {

        if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
            return json(['code' => 1, 'message' => '文件上传类型受限', 'data' => '']);
        }
        $pathinfo = pathinfo($file->getInfo('name'));
        $ext = strtolower(pathinfo($file->getInfo('name'), 4));
        $names = str_split($file->hash(), 16);

        $filename = "{$names[0]}/{$names[1]}.{$ext}";
        $savename = $names[1] . '.' . $ext;

        // 文件上传处理
        if (($info = $file->move("static/upload/{$names[0]}", $savename, true))) {

            $object = "static/upload/$filename";

            //上传到阿里云oss
            FileService::oss($object, file_get_contents(Env::get('root_path') . $object));

            $site_url = FileService::getFileUrl($filename, 'local');

            $path = '/upload/' . $names[0] . '/' . $info->getSaveName();
//                print_dump($path);
//            if ($ext == 'jpg' || $ext == 'jpeg' || $ext == 'gif' || $ext == 'png') {
//                //裁剪图片
//                image_edit($path, 1000, 0);
//            }

            $data = [
                'filename' => $pathinfo['filename'] . '.' . $ext,
//                    'url' => request()->root(true) . $site_url,
                'url' => $site_url,
            ];
            if ($type == 1) {
                $pics[] = $data;
            } else {
                $pics[] = $site_url;
            }


        }

    }

    return $pics;
}


/**
 * 多文件上传图片(qiniu)
 * @param $files
 * @param string $type
 * @return array
 */
function upload_files_by_qiniu($files, $type = 0)
{
    $pics = [];
    foreach ($files as $file) {

        if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
            return json(['code' => 1, 'message' => '文件上传类型受限', 'data' => '']);
        }
        $pathinfo = pathinfo($file->getInfo('name'));
        $ext = strtolower(pathinfo($file->getInfo('name'), 4));
        $names = str_split($file->hash(), 16);
        $tmp_name = $file->getInfo('tmp_name');
        $filename = "{$names[0]}/{$names[1]}.{$ext}";

        $object = "static/upload/$filename";

        //上传到七牛
//        FileService::oss($object, file_get_contents(Env::get('root_path') . $object));
        FileService::qiniu($object, file_get_contents($tmp_name));
        $site_url = FileService::getBaseUriQiniu() . $object;

        $data = [
            'filename' => $pathinfo['filename'] . '.' . $ext,
            'url' => $site_url,
        ];
        if ($type == 1) {
            $pics[] = $data;
        } else {
            $pics[] = $site_url;
        }

    }

    return $pics;
}

/**
 * 多文件上传图片(oss)
 * @param $files
 * @param string $type
 * @return array
 */
function upload_files_by_oss($files, $type = 0)
{
    $pics = [];
    foreach ($files as $file) {

        if (!$file->checkExt(strtolower(sysconf('storage_local_exts')))) {
            return json(['code' => 1, 'message' => '文件上传类型受限', 'data' => '']);
        }
        $pathinfo = pathinfo($file->getInfo('name'));
        $ext = strtolower(pathinfo($file->getInfo('name'), 4));
        $names = str_split($file->hash(), 16);
        $tmp_name = $file->getInfo('tmp_name');
        $filename = "{$names[0]}/{$names[1]}.{$ext}";

        $object = "static/upload/$filename";

        //上传到阿里云oss
//        FileService::oss($object, file_get_contents(Env::get('root_path') . $object));
        FileService::oss($object, file_get_contents($tmp_name));
        $site_url = FileService::getBaseUriOss() . $object;

        $data = [
            'filename' => $pathinfo['filename'] . '.' . $ext,
            'url' => $site_url,
        ];
        if ($type == 1) {
            $pics[] = $data;
        } else {
            $pics[] = $site_url;
        }

    }

    return $pics;
}


/**
 * 生成缩略图
 * @param $path
 * @param int $width
 * @param int $height
 */
function image_edit($path, $width = 200, $height = 200)
{
    $image = Image::open(Env::get('root_path') . 'static' . $path);
    $image->thumb($width, $height, Image::THUMB_SCALING)->save(Env::get('root_path') . '/static' . $path);
}


/**
 * 生成缩略图
 * @param $path
 * @param int $width
 * @param int $height
 */
function image_edit2($path, $width = 200, $height = 200)
{
    $image = Image::open(Env::get('root_path') . $path);

    $date_path = 'static/upload/thumb/' . date('Ymd');
    if (!file_exists($date_path)) {
        mkdir($date_path, 0777, true);
    }
    $thumb_path = $date_path . '/' . md5($path) . time() . '.jpg';
//    $image->thumb($width, $height, Image::THUMB_FILLED)->save($thumb_path);
//    $image->thumb($width, $height, Image::THUMB_CENTER)->save($thumb_path);
    $image->thumb($width, $height, Image::THUMB_NORTHWEST)->save($thumb_path);
//    $data['thumb_img'] = $thumb_path;

    $appRoot = request()->root(true); // 如果你想获取相对url地址，这里去掉参数 true
    $uriRoot = preg_match('/\.php$/', $appRoot) ? dirname($appRoot) : $appRoot;

    return $uriRoot . '/' . $thumb_path;

    $image->thumb($width, $height, Image::THUMB_FIXED)->save(Env::get('root_path') . $path);
}

/**
 * 替换表情
 * @param $str
 * @return string
 */
function replace_emoji2($str)
{
    preg_match_all('/\[emoji_lyh_(.*?)]/i', $str, $mat);
    for ($i = 0; $i < count($mat[1]); $i++) {
        $one = str_replace($mat[0][$i], '<img src="/static/images/emoji/' . $mat[1][$i] . '.gif">', $mat[0][$i]);
        $str = str_replace($mat[0][$i], $one, $str);
    }
    return $str;

}

/**
 * 替换表情
 * @param $str
 * @return string
 */
function replace_emoji($str)
{
    preg_match_all('/\[emoji_lyh_(.*?)]/i', $str, $mat);
    for ($i = 0; $i < count($mat[1]); $i++) {
        $one = str_replace($mat[0][$i], '<img src="/static/images/png/expression_' . $mat[1][$i] . '.png">', $mat[0][$i]);
        $str = str_replace($mat[0][$i], $one, $str);
    }
    return $str;

}


/**
 * 替换表情
 * @param $str
 * @return string
 */
function replace_emoji3($str)
{
    $emoji = [
        'emoji_lyh_1' => '[微笑]',
        'emoji_lyh_2' => '[撇嘴]',
        'emoji_lyh_3' => '[色]',
        'emoji_lyh_4' => '[发呆]',
        'emoji_lyh_5' => '[得意]',
        'emoji_lyh_6' => '[流泪]',
        'emoji_lyh_7' => '[害羞]',
        'emoji_lyh_8' => '[闭嘴]',
        'emoji_lyh_9' => '[睡]',
        'emoji_lyh_10' => '[大哭]',
        'emoji_lyh_11' => '[尴尬]',
        'emoji_lyh_12' => '[发怒]',
    ];

    preg_match_all('/\[emoji_lyh_(.*?)]/i', $str, $mat);
    for ($i = 0; $i < count($mat[1]); $i++) {
        $one = str_replace($mat[0][$i], '<img src="/static/images/png/expression_' . $mat[1][$i] . '.png">', $mat[0][$i]);
        $str = str_replace($mat[0][$i], $one, $str);
    }
    return $str;

    foreach ($emoji as $key => $row) {

        $isin = in_array($fen, $row);
        if ($isin) {
        }

        return $key;
    }

}

/**
 * 长链接生成段链接
 * @param $url
 * @return mixed
 */
function short_url($url)
{

    $config = [
        'appid' => config('wechat.appid'),
        'appsecret' => config('wechat.appsecret'),
    ];

    $wechat = new \WeChat\Qrcode($config);
    $ret = $wechat->shortUrl($url);
    if ($ret['errcode'] == 0) {
        return $ret['short_url'];
    } else {
        return $url;
    }

}


/**
 * 极光推送
 * @param string $alias
 * @param string $title
 * @param string $content
 * @param array $extras
 * @return array
 */
function sendOne($alias = '0', $title = '有新消息', $content = '', $extras = array())
{
    $config = config('jpush.');
    $client = new JPush($config['key'], $config['secret']);

    $response = $client->push()->setPlatform(array('ios', 'android'))
        ->addAlias((string)$alias)
        ->iosNotification($title, array(
            'sound' => 'default',
            'badge' => '+1',
//            'category' => 'jiguang',
            'extras' => $extras,
        ))
        ->androidNotification($content, array(
            'title' => $title,
            // 'builder_id' => 2,
            'extras' => $extras,
        ))
        ->options(array(
            'apns_production' => Env::get('apns_production', true), //false开发环境 true 生产环境
        ))
        ->send();

    return $response;
}

/**
 * 生成一个不会重复的字符串
 * @return string
 */
function setKey()
{
    $str = md5(uniqid(md5(microtime(true)), true));
    $str = sha1($str);  //加密
    return $str;
}

/**
 * 数组排序
 * @param $data
 * @param $sort_order_field
 * @param int $sort_order
 * @param int $sort_type
 * @return mixed
 */
function array_sort($data, $sort_order_field, $sort_order = SORT_ASC, $sort_type = SORT_NUMERIC)
{
    foreach ($data as $val) {
        $key_arrays[] = $val[$sort_order_field];
    }
    array_multisort($key_arrays, $sort_order, $sort_type, $data);
    return $data;
}


/**
 * 定界符
 * @return string
 */
function images()
{
    $path = config('template.tpl_replace_string.__STATIC__');

    $str =
        <<<EOF
            <p class="imgWrap">"$path/uploads/20180716/74e820a603eef9df6819c03f861def1e.jpg" style="width:110px;height:110px"></p>
EOF;
    return $str;
}


/**
 * 隐藏手机号
 * @param $phone
 * @return mixed
 */
function hidTel($phone)
{
    $IsWhat = preg_match('/(0[0-9]{2,3}[\-]?[2-9][0-9]{6,7}[\-]?[0-9]?)/i', $phone); //固定电话
    if ($IsWhat == 1) {
        return preg_replace('/(0[0-9]{2,3}[\-]?[2-9])[0-9]{3,4}([0-9]{3}[\-]?[0-9]?)/i', '$1****$2', $phone);
    } else {
        return preg_replace('/(1[358]{1}[0-9])[0-9]{4}([0-9]{4})/i', '$1****$2', $phone);
    }
}


/**
 * 只保留字符串首尾字符，隐藏中间用*代替（两个字符时只显示第一个）
 * @param string $user_name 姓名
 * @return string 格式化后的姓名
 */
function hidName($user_name)
{
    $strlen = mb_strlen($user_name, 'utf-8');
    $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
    $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
    return $strlen == 2 ? $firstStr . str_repeat('*', mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
}


function WxSign($params, $key)
{
    ksort($params);
    $unSignParaString = FormatQueryParaMap($params, false);
    $signStr = $unSignParaString . "&key=" . $key;
    return strtoupper(md5($signStr));
}

function FormatQueryParaMap($paraMap, $urlencode)
{
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v) {
        if (null != $v && "null" != $v && "sign" != $k) {
            if ($urlencode) {
                $v = urlencode($v);
            }
            $buff .= $k . "=" . $v . "&";
        }
    }
    $reqPar = null;
    if (strlen($buff) > 0) {
        $reqPar = substr($buff, 0, strlen($buff) - 1);
    }
    return $reqPar;
}